#!/usr/bin/env python
import re, requests, os
from pprint import pprint

url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8999'
pre = 'stations_pre.py'
cur = 'stations.py'


def doUpdate():
    try:
        response = requests.get(url, verify=False)
        stations = re.findall(u'([\u4e00-\u9fa5]+)\|([A-Z]+)', response.text)
        f = open(pre, 'w')
        f.write('stations = ')
        pprint(dict(stations), stream=f, indent=4)
    except IOError as e:
        if f:
            f.close()
        os.remove(pre)
        print("Error!"+str(e))
    else:
        f.close()
        os.rename(pre, cur)


if __name__ == '__main__':
    doUpdate()
